package com.example.team1metricsclient;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.codehaus.jettison.json.JSONArray;
import org.codehaus.jettison.json.JSONException;
import org.codehaus.jettison.json.JSONObject;
import org.vaadin.vaadinvisualizations.BarChart;

import com.vaadin.annotations.AutoGenerated;
import com.vaadin.data.Property;
import com.vaadin.data.Property.ValueChangeEvent;
import com.vaadin.ui.AbstractSelect.Filtering;
import com.vaadin.ui.Button;
import com.vaadin.ui.Button.ClickEvent;
import com.vaadin.ui.Button.ClickListener;
import com.vaadin.ui.ComboBox;
import com.vaadin.ui.CustomComponent;
import com.vaadin.ui.GridLayout;
import com.vaadin.ui.HorizontalLayout;
import com.vaadin.ui.Label;
import com.vaadin.ui.TabSheet;
import com.vaadin.ui.TabSheet.SelectedTabChangeEvent;
import com.vaadin.ui.Table;
import com.vaadin.ui.TextField;
import com.vaadin.ui.VerticalLayout;

public class MainLayout extends CustomComponent implements
ClickListener, TabSheet.SelectedTabChangeListener  {

	@AutoGenerated
	private VerticalLayout mainLayout;
	private VerticalLayout graphLayout;
	private GridLayout labelgrid, kernelinfo;
	@AutoGenerated
	private TabSheet Metrics;
	@AutoGenerated
	private ComboBox metricsList,logList, cpu;
	@AutoGenerated
	private VerticalLayout logTab;
	private Table table,table1;
	private VerticalLayout metricsTab;
	@AutoGenerated
	private Button search,show;
	@AutoGenerated
	private TextField textKeyWord;
	@AutoGenerated
	private Label logLabel;
	private BarChart bc,logbc;
	private static final String[] metricsTypes = new String[] { "cpu.usage.avg", "cpu.used.summation",
        "cpu.utilization.average", "mem.usage.average", "disk.usage.average", "net.usage.average", "sys.heartbeat.summation", "sys.resourcecpuusage.average", "storagepath.read.average", "storagepath.write.average", "virtualdisk.readOIO.latest", "virtualdisk.writeOIO.latest", "power.power.average"};


	/*- VaadinEditorProperties={"grid":"RegularGrid,20","showGrid":true,"snapToGrid":true,"snapToObject":true,"movingGuides":false,"snappingDistance":10} */

	/**
	 * 
	 */
	private static final long serialVersionUID = 3211263039259179634L;
	/**
	 * The constructor should first build the main layout, set the
	 * composition root and then do any custom initialization.
	 *
	 * The constructor will not be automatically regenerated by the
	 * visual editor.
	 */
	public MainLayout() {
		buildMainLayout();
		setCompositionRoot(mainLayout);
	}

	@AutoGenerated
	private VerticalLayout buildMainLayout() {
		// common part: create layout
		mainLayout = new VerticalLayout();
		mainLayout.setImmediate(false);
		mainLayout.setWidth("100%");
		mainLayout.setHeight("100%");
		mainLayout.setMargin(false);
		
		// top-level component properties
		setWidth("100.0%");
		setHeight("100.0%");
		
		// Metrics
		Metrics = buildMetrics();
		mainLayout.addComponent(Metrics);		
		return mainLayout;
	}

	@AutoGenerated
	private TabSheet buildMetrics() {
		// common part: create layout
		Metrics = new TabSheet();
		Metrics.addListener(this);
		Metrics.setImmediate(true);
		Metrics.setWidth("100%");
		Metrics.setHeight("100%");
		
		
		// metricsTab
		metricsTab = buildMetricsTab();
		Metrics.addTab(metricsTab, "Metrics", null);
		
		// logTab
		logTab = buildLogTab();
		Metrics.addTab(logTab, "Logs", null);
		
		
		return Metrics;
	}

	@AutoGenerated
	private VerticalLayout buildMetricsTab() {
		// comboBox_2
		metricsTab = new VerticalLayout();
		metricsTab.setImmediate(true);
		metricsTab.setMargin(false);
		metricsList = new ComboBox("Please select a Metric type");
		for (int i = 0; i < metricsTypes.length; i++) {
			metricsList.addItem(metricsTypes[i]);
        }

		metricsList.setFilteringMode(Filtering.FILTERINGMODE_OFF);
		metricsList.setImmediate(true);
		//metricsList.addListener(this);
		//metricsList.setImmediate(false);
		metricsList.setWidth("-1px");
		metricsList.setHeight("-1px");
		//metricsList.addListener(this);
		
		show = new Button();
		show.setCaption("Show Graph");
		show.setImmediate(true);
		show.setWidth("-1px");
		show.setHeight("-1px");
		show.addListener(this);
		
		metricsTab.addComponent(metricsList);
		metricsTab.addComponent(show);
		return metricsTab;
	}
	@AutoGenerated
	private VerticalLayout buildLogTab() {
		// common part: create layout
		logTab = new VerticalLayout();
		logTab.setImmediate(false);
		logTab.setMargin(false);
		logList = new ComboBox("Please select a Log type");
		logList.addItem("KernelLog");
		logList.addItem("SysLog");
		logList.addItem("KernelWarning");
		logList.addItem("Hostd");
		logList.addListener(new Property.ValueChangeListener() {
			private static final long serialVersionUID = 8682697990013330276L;
			public void valueChange(ValueChangeEvent event) {
				if (cpu != null)
					logTab.removeComponent(cpu);
				if(logbc != null)
					logTab.removeComponent(logbc);
				if(labelgrid != null)
					logTab.removeComponent(labelgrid);
				if(table != null)
					logTab.removeComponent(table);
				if(table1 != null)
					logTab.removeComponent(table1);
				String logType = (String) logList.getValue();
				if (logType.equals("KernelLog") || logType.equals("KernelWarning")){
					logTab.removeComponent(logLabel);
					logTab.removeComponent(textKeyWord);
					cpu = new ComboBox("Select a CPU");
	        		cpu.addItem("cpu0");
	        		cpu.addItem("cpu1");
	        		cpu.addItem("cpu2");
	        		cpu.addItem("cpu3");
	        		cpu.setImmediate(true);
	        		logTab.addComponent(cpu);
				}else{
					logTab.addComponent(logLabel);
					logTab.addComponent(textKeyWord);
				}
			}
        });
		logTab.addComponent(logList);
		
		
		// logLabel
		logLabel = new Label();
		logLabel.setImmediate(true);
		logLabel.setWidth("-1px");
		logLabel.setHeight("-1px");
		logLabel.setValue("Enter Keyword");
		logTab.addComponent(logLabel);
		
		// textKeyWord
		textKeyWord = new TextField();
		textKeyWord.setImmediate(false);
		textKeyWord.setWidth("-1px");
		textKeyWord.setHeight("-1px");
		textKeyWord.setSecret(false);
		logTab.addComponent(textKeyWord);
		
		// search
		search = new Button();
		search.setCaption("Search Log");
		search.setImmediate(true);
		search.setWidth("-1px");
		search.setHeight("-1px");
		search.addListener(this);
		logTab.addComponent(search);
		
		return logTab;
	}

	public void buttonClick(ClickEvent event) {
		
		String output=null,ts1=null,ts2=null,ts3 = null, logtime, output2 =null;
		Long time;
		
		if (event.getButton() == show){
			String name = (String) metricsList.getValue();
			getWindow().showNotification("Selected value: " + name);
			if(bc != null)
				metricsTab.removeComponent(bc);
//			if(logbc != null)
//				getWindow().removeComponent(logbc);
			
			try {
				 
				URL url = new URL("http://localhost/MetricsService/get/metrics");
				HttpURLConnection conn = (HttpURLConnection) url.openConnection();
				conn.setRequestMethod("GET");
				conn.setRequestProperty("Accept", "application/json");
		 
				if (conn.getResponseCode() != 200) {
					throw new RuntimeException("Failed : HTTP error code : "
							+ conn.getResponseCode());
				}
		 
				BufferedReader br = new BufferedReader(new InputStreamReader(
					(conn.getInputStream())));	 
				
				
				System.out.println("Output from Server .... \n");
				if ((output = br.readLine()) != null) {
					System.out.println(output);				
					JSONObject jo = new JSONObject(output);
					time = jo.getLong("sampleTime");
					Date date1 = new Date(time);
					Date date2 = new Date(time+20000);
					Date date3 = new Date(time+40000);
					System.out.println("time1 from json "+date1);
					System.out.println("time2 from json "+date2);
					System.out.println("time3 from json "+date3);
					SimpleDateFormat sdf = new SimpleDateFormat("MMM dd,yyyy HH:mm:ss");
					
					ts1 = sdf.format(date1);
					ts2 = sdf.format(date2);
					ts3 = sdf.format(date3);
					
					JSONArray counter = jo.getJSONArray("counter");
					System.out.println("array length "+counter.length());
					for (int i=0;i<counter.length();i++){
						JSONObject obj = counter.getJSONObject(i);
						if(obj.getString("name").equalsIgnoreCase(name)){
							System.out.println("inside if----------------------"+obj.getLong("sample1") );
						    bc = new BarChart();
						    bc.setImmediate(true);
					        bc.setOption("is3D", true);
							bc.addXAxisLabel("Time");
							bc.addBar(obj.getString("unit"));
							bc.add(ts1.toString(), new double[]{(double)obj.getLong("sample1")});
					        bc.add(ts2.toString(), new double[]{(double)obj.getLong("sample2")});
					        bc.add(ts3.toString(), new double[]{(double)obj.getLong("sample3")});
					        bc.setSizeFull();
							bc.setVisible(true);
							metricsTab.addComponent(bc);
							//getWindow().addComponent(bc);
							//getWindow().
					        break;
						}
						
					}			
				}
				conn.disconnect();
				 
			  } catch (MalformedURLException e) {	 
				e.printStackTrace();	 
			  } catch (IOException e) {	 
				e.printStackTrace();	 
			  } catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		 
		}
		if (event.getButton() == search){
			if(logbc != null)
				logTab.removeComponent(logbc);
			if(labelgrid != null)
				logTab.removeComponent(labelgrid);
			if(table != null)
				logTab.removeComponent(table);
			if(table1 != null)
				logTab.removeComponent(table1);
			
			System.out.println("in search log");
			String logType = (String) logList.getValue();
			if (logType.equals("KernelLog") || logType.equals("KernelWarning")){
				System.out.println("in kernel if");
				String cpuType = (String)cpu.getValue();			
				if (logType.equals("KernelLog")){
					System.out.println("in KernelLog if");
					try {
						URL url = new URL("http://localhost/MetricsService/get/logmetrics/kernelLogs/cpu?cpu="+cpuType);
						HttpURLConnection conn = (HttpURLConnection) url.openConnection();
						conn.setRequestMethod("GET");				
						conn.setRequestProperty("Accept", "application/json");				 
						if (conn.getResponseCode() != 200) {
							throw new RuntimeException("Failed : HTTP error code : "
									+ conn.getResponseCode());
						}
						BufferedReader br = new BufferedReader(new InputStreamReader((conn.getInputStream())));	
						if ((output = br.readLine()) != null){
							System.out.println("output -"+output);
							JSONArray ja = new JSONArray(output);
							table = new Table("Kernel Logs");
							table.addContainerProperty("date_time", String.class,  null);
							table.addContainerProperty("host_uptime",  String.class,  null);
							table.addContainerProperty("cpuName",       String.class, null);
							table.addContainerProperty("wid", String.class,  null);
							table.addContainerProperty("code_reporting_message",  String.class,  null);
							table.addContainerProperty("lineNum",       String.class, null);
							table.addContainerProperty("messageContent", String.class,  null);
							
							for (int i=0;i<ja.length();i++){
								JSONObject jobj = ja.getJSONObject(i);
								String date_time = jobj.getString("date_time");
								String host_uptime = jobj.getString("host_uptime");
								String cpuName = jobj.getString("cpuName");
								String wid = jobj.getString("wid");
								String code_reporting_message = jobj.getString("code_reporting_message");
								String lineNum = jobj.getString("lineNum");
								String messageContent = jobj.getString("messageContent");
								table.addItem(new Object[] {
										date_time,host_uptime,cpuName,wid,code_reporting_message,lineNum,messageContent}, new Integer(i+1));

							}
							logTab.addComponent(table);
						}
						conn.disconnect();
					}catch (MalformedURLException e) {	 
						e.printStackTrace();	 
					  } catch (IOException e) {	 
						e.printStackTrace();	 
					  } catch (JSONException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					  
				}
				if (logType.equals("KernelWarning")){
					System.out.println("in KernelWarning if");
					try {
						URL url = new URL("http://localhost/MetricsService/get/logmetrics/kernelWarnings/cpu?cpu="+cpuType);
						HttpURLConnection conn = (HttpURLConnection) url.openConnection();
						conn.setRequestMethod("GET");				
						conn.setRequestProperty("Accept", "application/json");				 
						if (conn.getResponseCode() != 200) {
							throw new RuntimeException("Failed : HTTP error code : "
									+ conn.getResponseCode());
						}
						BufferedReader br = new BufferedReader(new InputStreamReader((conn.getInputStream())));	
						if ((output = br.readLine()) != null){
							System.out.println("output -"+output);
							JSONArray ja = new JSONArray(output);
							table1 = new Table("Kernel Warning Logs");
							table1.addContainerProperty("date_time", String.class,  null);
							table1.addContainerProperty("host_uptime",  String.class,  null);
							table1.addContainerProperty("cpuName",       String.class, null);
							table1.addContainerProperty("wid", String.class,  null);
							table1.addContainerProperty("code_reporting_message",  String.class,  null);
							table1.addContainerProperty("lineNum",       String.class, null);
							table1.addContainerProperty("messageContent", String.class,  null);
							
							for (int i=0;i<ja.length();i++){
								JSONObject jobj = ja.getJSONObject(i);
								String date_time = jobj.getString("date_time");
								String host_uptime = jobj.getString("host_uptime");
								String cpuName = jobj.getString("cpuName");
								String wid = jobj.getString("wid");
								String code_reporting_message = jobj.getString("code_reporting_message");
								String lineNum = jobj.getString("lineNum");
								String messageContent = jobj.getString("messageContent");
								table1.addItem(new Object[] {
										date_time,host_uptime,cpuName,wid,code_reporting_message,lineNum,messageContent}, new Integer(i+1));

							}
							logTab.addComponent(table1);
						}
						conn.disconnect();
					}catch (MalformedURLException e) {	 
						e.printStackTrace();	 
					  } catch (IOException e) {	 
						e.printStackTrace();	 
					  } catch (JSONException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					  
				}
				
			}else {
				String value = (String) textKeyWord.getValue();
				System.out.println("in search log-"+value);
				
	//				getWindow().removeComponent(logbc);logmetrics/syslogs/kwcount logmetrics/syslog/lines
				try {
				URL url1 = new URL("http://localhost/MetricsService/get/logmetrics/syslogs/kwcount?keyword="+value);
				URL url2 = new URL("http://localhost/MetricsService/get/logmetrics/syslogs/lines?keyword="+value);
				HttpURLConnection conn1 = (HttpURLConnection) url1.openConnection();
				HttpURLConnection conn2 = (HttpURLConnection) url2.openConnection();
				conn1.setRequestMethod("GET");
				conn2.setRequestMethod("GET");
				conn1.setRequestProperty("Accept", "application/json");
				conn2.setRequestProperty("Accept", "application/json");
		 
				if (conn1.getResponseCode() != 200) {
					throw new RuntimeException("Failed : HTTP error code : "
							+ conn1.getResponseCode());
				}
				if (conn2.getResponseCode() != 200) {
					throw new RuntimeException("Failed : HTTP error code : "
							+ conn2.getResponseCode());
				}
		 
				BufferedReader br = new BufferedReader(new InputStreamReader(
					(conn1.getInputStream())));	 
				BufferedReader br2 = new BufferedReader(new InputStreamReader(
						(conn2.getInputStream())));	 
				
				
				System.out.println("Output from  server for log search....\n");
				if ((output = br.readLine()) != null && (output2 = br2.readLine()) != null) {
					System.out.println("Output -"+output);	
					System.out.println("Output2 -"+output2);	
					JSONArray ja = new JSONArray(output);
					//graphLayout = new VerticalLayout();
					logbc = new BarChart();
					logbc.setImmediate(true);
					logbc.setOption("is3D", true);
					logbc.addXAxisLabel("Time");
					logbc.addBar("NoOfOccurrences");
					for (int i=0;i<ja.length();i++){
						JSONObject jobj = ja.getJSONObject(i);
						logtime = jobj.getString("timeStamp");					
						if (logtime.toString() != null){
							logbc.add(logtime.toString(), new double[]{jobj.getDouble("noOfOccurences")});
						}
					}
					logbc.setSizeFull();
					logbc.setVisible(true);
					logTab.addComponent(logbc); 
					//getWindow().addComponent(logbc);
					//graphLayout.addComponent(logbc);
					//logTab.addComponent(graphLayout);				
					JSONArray ja1 = new JSONArray(output2);
					labelgrid = new GridLayout (2,1);
					for (int i=0;i<ja1.length();i++){
						JSONObject jobj = ja1.getJSONObject(i);
						String date = jobj.getString("date_time");
						String message = jobj.getString("line");
						labelgrid.addComponent (new Label (date));
						labelgrid.addComponent (new Label (message));
					}				
					
					logTab.addComponent(labelgrid);
									
					}			
				
				conn1.disconnect();
				conn2.disconnect();
				}catch (MalformedURLException e) {	 
					e.printStackTrace();	 
				  } catch (IOException e) {	 
					e.printStackTrace();	 
				  } catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
	}
	}

	public void selectedTabChange(SelectedTabChangeEvent event) {
		// TODO Auto-generated method stub
		//if(logbc != null)
		//getWindow().removeComponent(logbc);
	
		
	}
	
	

}

////********** - Kavya- **************
//
//Container.Indexed container = new IndexedContainer();
//// Add the required property ids, we use the default ones here
//container.addContainerProperty(Timeline.PropertyId.TIMESTAMP,
//Date.class, null);
//container.addContainerProperty(Timeline.PropertyId.VALUE,
//Integer.class, 0f);
//
//
//Calendar cal = Calendar.getInstance();
//cal.add(Calendar.MONTH, -1);
//Date today = new Date();
//
//// Add some random data to the container
//Item item = container.addItem(cal.getTime());
//
//
//
//
//// Set the timestamp property
//item.getItemProperty(Timeline.PropertyId.TIMESTAMP).setValue(new Date());
//
//// Set the value property
//item.getItemProperty(Timeline.PropertyId.VALUE).setValue(new Integer(1));
//
//// Set the timestamp property
////item.getItemProperty(Timeline.PropertyId.TIMESTAMP).setValue(new Timestamp(2012,1,12,12,56,23,12));
//item.getItemProperty(Timeline.PropertyId.TIMESTAMP).setValue(new Date());
//
//// Set the value property
//item.getItemProperty(Timeline.PropertyId.VALUE).setValue(new Integer(200));
//
//// Set the timestamp property
//item.getItemProperty(Timeline.PropertyId.TIMESTAMP).setValue(new Date());
//
//// Set the value property
//item.getItemProperty(Timeline.PropertyId.VALUE).setValue(new Integer(1000));
//
//
//
//
//Timeline timeline = new Timeline("Our timeline");
//
//timeline.setWidth("100%");
//timeline.addGraphDataSource(container,
//		Timeline.PropertyId.TIMESTAMP,
//		Timeline.PropertyId.VALUE);
//timeline.selectFullRange();
//timeline.setClientCacheEnabled(false);
//timeline.setSizeUndefined();//setSizeFull();

//public void valueChange(ValueChangeEvent event) {
//// TODO Auto-generated method stub
//getWindow().showNotification("Selected value: " + metricsList.getValue());
//bc.setVisible(true);
//}

//labelgrid.addComponent (new Label ("CONTENT_DEFAULT"));
//labelgrid.addComponent (
//    new Label ("This is a label in default mode: <plain text>",
//               Label.CONTENT_DEFAULT));
//
//labelgrid.addComponent (new Label ("CONTENT_PREFORMATTED"));
//labelgrid.addComponent (
//    new Label ("This is a preformatted label.\n"+
//               "The newline character \\n breaks the line.",
//               Label.CONTENT_PREFORMATTED));
//
//labelgrid.addComponent (new Label ("CONTENT_RAW"));
//labelgrid.addComponent (
//    new Label ("This is a label in raw mode.<br>It can contain, "+
//               "for example, unbalanced markup.",
//               Label.CONTENT_RAW));
//
//labelgrid.addComponent (new Label ("CONTENT_TEXT"));
//labelgrid.addComponent (
//    new Label ("This is a label in (plain) text mode",
//               Label.CONTENT_TEXT));
//
//labelgrid.addComponent (new Label ("CONTENT_XHTML"));
//labelgrid.addComponent (
//    new Label ("<i>This</i> is an <b>XHTML</b> formatted label",
//               Label.CONTENT_XHTML));
//
//labelgrid.addComponent (new Label ("CONTENT_XML"));
//labelgrid.addComponent (
//    new Label ("This is an <myelement>XML</myelement> "+
//               "formatted label",
//               Label.CONTENT_XML));

//BufferedReader br = new BufferedReader(new InputStreamReader((conn.getInputStream())));	
//if ((output = br.readLine()) != null){
//	System.out.println("output -"+output);
//	JSONArray ja = new JSONArray(output);
//	kernelinfo = new GridLayout (7,1);
//	for (int i=0;i<ja.length();i++){
//		JSONObject jobj = ja.getJSONObject(i);
//		String date_time = jobj.getString("date_time");
//		String host_uptime = jobj.getString("host_uptime");
//		String cpuName = jobj.getString("cpuName");
//		String wid = jobj.getString("wid");
//		String code_reporting_message = jobj.getString("code_reporting_message");
//		String lineNum = jobj.getString("lineNum");
//		String messageContent = jobj.getString("messageContent");
//		kernelinfo.addComponent (new Label (date_time));
//		kernelinfo.addComponent (new Label (host_uptime));
//		kernelinfo.addComponent (new Label (cpuName));
//		kernelinfo.addComponent (new Label (code_reporting_message));
//		kernelinfo.addComponent (new Label (lineNum));
//		kernelinfo.addComponent (new Label (messageContent));
//		kernelinfo.addComponent (new Label (wid));
//	}
//	logTab.addComponent(kernelinfo);
//}
//conn.disconnect();
